using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using MEC;

public static class JsonDataLoader
{
    private static Dictionary<string, object> cache = new Dictionary<string, object>();
    private static Queue<string> loadOrder = new Queue<string>();
    private const int CacheThreshold = 8;

    public static CoroutineHandle LoadJson(string filePath, Action<string> onLoaded)
    {
        return Timing.RunCoroutine(_LoadJson(filePath, onLoaded));
    }

    private static IEnumerator<float> _LoadJson(string filePath, Action<string> onLoaded)
    {
        if (cache.ContainsKey(filePath))
        {
            onLoaded?.Invoke(cache[filePath] as string);
            yield break;
        }

        string path = Path.Combine(Application.streamingAssetsPath, filePath);
#if UNITY_EDITOR
        if (File.Exists(path))
        {
            string jsonContent = File.ReadAllText(path);
            AddToCache(filePath, jsonContent);
            onLoaded?.Invoke(jsonContent);
        }
        else
        {
            Debug.LogError($"Error loading JSON file: File not found at {path}");
        }
        yield return 0f;
#else
        UnityWebRequest request = UnityWebRequest.Get(path);
        yield return Timing.WaitUntilDone(request.SendWebRequest());

        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError($"Error loading JSON file: {request.error}");
        }
        else
        {
            var jsonContent = request.downloadHandler.text;
            AddToCache(filePath, jsonContent);
            onLoaded?.Invoke(jsonContent);
        }
#endif
    }

    private static void AddToCache(string key, string data)
    {
        if (cache.Count >= CacheThreshold)
        {
            string oldestKey = loadOrder.Dequeue();
            cache.Remove(oldestKey);
        }

        cache[key] = data;
        loadOrder.Enqueue(key);
    }
}